package com.example.workrecord.service;

import com.example.workrecord.common.Page;
import com.example.workrecord.dao.BaseJPA;
import com.example.workrecord.dao.GuestDao;
import com.example.workrecord.entity.*;
import com.example.workrecord.exption.BizException;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GuestService extends BaseService<Guest,Long>{
    @Autowired
    private GuestDao dao;
    @Autowired
    private AlumniService alumniService;

    @Autowired
    private JPAQueryFactory queryDslTool;

    @Override
    protected BaseJPA<Guest> getDao() {
        return dao;
    }
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void saveGuest(Guest guest) throws BizException {
        save(guest);
        List<Alumni> list=guest.getAlumniList();
        if(null == list|| list.size()==0){
            return;
        }
        for(Alumni alumni:list){
            alumni.setGuestId(guest.getId());
        }
        alumniService.saveAll(list);

    }
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void deleteGuest(Integer id) throws Exception{
        delete(Long.valueOf(id));
        alumniService.deleteByGuestId(Long.valueOf(id));
    }
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void eidtGuest(Guest guest) throws Exception{
        update(guest.getId(),guest);
        alumniService.eidit(guest.getAlumniList(),guest.getId());
    }

    public void findGuestByData(Guest vo, Page<Guest> page) {
        QGuest qGuest=QGuest.guest;
        JPAQuery<Guest> jpaQuery=queryDslTool.select(qGuest).from(qGuest);
        long count=jpaQuery.fetchCount();
        List<Guest> guests=jpaQuery.offset((page.getPageCurrent() - 1) * page.getPageSize())
                .limit(page.getPageSize())
                .fetch();
        for(Guest guest:guests){
            List<Alumni> alumnis=alumniService.findByGuestId(guest.getId());
            guest.setAlumniList(alumnis);
        }
        page.setList(guests);
        page.setTotal(count);
    }

    public Guest findGuestById(Guest guest) {
        guest=findById(guest.getId());
        List<Alumni> alumnis=alumniService.findByGuestId(guest.getId());
        guest.setAlumniList(alumnis);
        return guest;
    }
}
